//
//  JrdCourseDetailViewController.m
//  v2ex-iOS
//
//  Created by longcheng on 16/5/21.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdCourseDetailViewController.h"
#import "JrdCommon.h"
#import "MJRefresh.h"
#import "JrdCourseDetailInfoCell.h"
#import "JrdCourseNodeCellTableViewCell.h"
#import "JrdNodeModel.h"
#import "MusicModel.h"
#import "AudioPlayerController.h"
#import "JrdCourseInfoCellTableViewCell.h"
#import "Reachability.h"
#import "CKHttpCommunicate.h"
#import "JZCourseDetailModel.h"
#import "JZStepListModel.h"
#import "JZClassListModel.h"
#import "LCCSqliteManager.h"
#import "CLDownloadRequest.h"
#import "JrdQuestionViewController.h"
#import "JrdDatamanager.h"
#import "JrdDownloadModel.h"
static NSString *task1_URL = @"http://120.55.86.220/uploads/nodeResource/c.mp3";//@"http://dldir1.qq.com/qqfile/qq/QQ8.4/18357/QQ8.4.exe";

@interface JrdCourseDetailViewController ()<UITableViewDataSource,UITableViewDelegate,CLDownloadDelegate>{
    NSMutableArray* chapterListArray;
    NSMutableArray* nodeListArray;
    NSMutableArray* nodeList;
    NSInteger vHeadIndex;
    JZCourseDetailModel *_jzCourseDM;
    NSInteger vCourseInfoCellHeight;
    LCCSqliteManager* manager;
    //NSArray* nodeListData;
    NSMutableArray* nodeListData;
    NSInteger select_index;
    BOOL v_is_has_date;
    DownloadStatus v_download_status;
    NSString* v_download_audio_path;
    JrdCourseNodeCellTableViewCell *click_cell;
    NSMutableArray* m_download_list;
    BOOL v_edit_mode;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) SCBarButtonItem *rightBarItem;
//Fake Data
@property (nonatomic, strong) NSMutableArray *songArray;
@property (nonatomic, strong) UITextView *learn_time_label;
@end

@implementation JrdCourseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;
    self.sc_navigationItem.rightBarButtonItem = self.rightBarItem;
    if(([_coursemodel.courseStartTime isEqualToString:@""]&&[_coursemodel.courseEndTime isEqualToString:@""]) || JRD_CHECK_VALUE == [[JrdDatamanager manager] getCheckValue]){
        v_is_has_date=false;
    }else{
        v_is_has_date = true;
    }
    v_download_status = DOWNLOAD_NONE;
    m_download_list = [[NSMutableArray alloc] init];
    v_edit_mode = false;
}

- (void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadData)
                                                 name:kReloadDataNotification
                                               object:nil];

}

- (void)viewDidDisappear:(BOOL)animated{

}

- (void)reloadData{
    if(ENTER_FROM_DOWNLOAD != _enter_type){
        NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                      _coursemodel.courseId,[JrdDatamanager manager].user.userId];
        nodeListData= (NSMutableArray*)[manager searchDataFromSheet:@"nodelist" where:searchCondition];
    }else{
        NSString * searchCondition = [NSString stringWithFormat:@"is_download=%@",
                                      @(1)];
        nodeListData= (NSMutableArray*)[manager searchDataFromSheet:@"nodelist" where:searchCondition];
    }

    [self sortNodeList];
    if(nil != nodeListData && 0 != nodeListData.count){
        [self.songArray removeAllObjects];
        for(int i =0; i < nodeListData.count; i++){
            MusicModel *model = [[MusicModel alloc] init];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            model.course_id = [numberFormatter numberFromString:_coursemodel.courseId];
            model.chapter_id = [NSNumber numberWithInt:0];
            model.music_id = nodeListData[i][0];
            model.fileName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_AUDIO_URL]];
            model.docName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_DOC_URL]];
            model.singer = nodeListData[i][NODE_LEVEL_ID];
            
            if(1 == [nodeListData[i][NODE_IS_DOWNLOAD] intValue]){
                model.localPath = nodeListData[i][NODE_DOWNLOAD_URL];
            }
            [self.songArray addObject:model];
        }
    }

    [self.tableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [self.tableView reloadData];
    self.sc_navigationItem.title = _coursemodel.courseName;
}


- (void)loadView{
    v_edit_mode = false;
    [super loadView];
    [self initData];
    manager = [LCCSqliteManager shareInstance];
    //[manager openSqliteFile:@"database"];
    if(ENTER_FROM_DOWNLOAD != _enter_type){
        NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                      _coursemodel.courseId, [JrdDatamanager manager].user.userId];

        nodeListData = (NSMutableArray*)[manager searchDataFromSheet:@"nodelist" where:searchCondition];
    }else{
        NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and is_download=%@",
                                     _coursemodel.courseId,  @(1)];
        nodeListData= (NSMutableArray*)[manager searchDataFromSheet:@"nodelist" where:searchCondition];
    }
    if(nil != nodeListData && 0 != nodeListData.count){
        [self.songArray removeAllObjects];
        for(int i =0; i < nodeListData.count; i++){
            MusicModel *model = [[MusicModel alloc] init];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            model.course_id = [numberFormatter numberFromString:_coursemodel.courseId];
            model.chapter_id = [NSNumber numberWithInt:0];
            model.music_id = nodeListData[i][0];
            model.fileName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_AUDIO_URL]];
            model.docName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_DOC_URL]];
            model.singer = nodeListData[i][NODE_LEVEL_ID];

            if(1 == [nodeListData[i][NODE_IS_DOWNLOAD] intValue]){
                model.localPath = nodeListData[i][NODE_DOWNLOAD_URL];
            }
            [self.songArray addObject:model];
        }
    }

    [self sortNodeList];
    if(nil != nodeListData && 0 != nodeListData.count){
        [self.songArray removeAllObjects];
        for(int i =0; i < nodeListData.count; i++){
            MusicModel *model = [[MusicModel alloc] init];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            model.course_id = [numberFormatter numberFromString:_coursemodel.courseId];
            model.chapter_id = [NSNumber numberWithInt:0];
            model.music_id = nodeListData[i][0];
            model.fileName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_AUDIO_URL]];
            model.docName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_DOC_URL]];
            model.singer = nodeListData[i][NODE_LEVEL_ID];

            if(1 == [nodeListData[i][NODE_IS_DOWNLOAD] intValue]){
                model.localPath = nodeListData[i][NODE_DOWNLOAD_URL];
            }
            [self.songArray addObject:model];
        }
    }
    [self initTableView];
    [self configureNav];

}

- (void)initView{
    self.learn_time_label = [[UITextView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 45)];
    self.learn_time_label.textAlignment=NSTextAlignmentRight;
    
}
- (void)initData{
    chapterListArray = [[NSMutableArray alloc] init];
    nodeListArray = [[NSMutableArray alloc] init];
    vHeadIndex = 0;
}

- (void)configureNav{
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_back"] highlight:[UIImage imageNamed:@"btn-back-press"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [self.navigationController popViewControllerAnimated:YES];
        if(ENTER_FROM_DOWNLOAD == _enter_type){
            if(0 == nodeListData.count){
                NSString * searchConditionExt = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                                 _coursemodel.courseId, [JrdDatamanager manager].user.userId];
                Boolean retExt = [manager updateDataToSheet_couse_download:@"courselist" withData:@[@(0)] where:searchConditionExt];
                NSLog(@"%d", retExt);
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateDownloadInfoNotification object:self];

            }
        }else{
            if(0!=nodeListData.count){
                v_download_status = DOWNLOAD_NONE;
                
                NSString* url_string = nodeListData[select_index][NODE_AUDIO_URL];
                NSString* task_url = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_string];
                NSString* doc_name = [task_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                CLDownloadRequest *request = [CLDownloadRequest initWithURL:doc_name];
                if (CLDownloadRequestState_Loading == request.state) {
                    [request cancelDownload];
                    return;
                }

            }
        }
    }];
    
    if(ENTER_FROM_DOWNLOAD == _enter_type){
        self.rightBarItem = [[SCBarButtonItem alloc] initWithTitle:NSLocalizedString(@"jrd_edit", nil) style:SCBarButtonItemStylePlain handler:^(id sender){
            if(false == v_edit_mode){
                v_edit_mode = true;
                [self.tableView setEditing:YES animated:YES];
                [self.rightBarItem updateTitle:NSLocalizedString(@"jrd_done", nil)];
            }else{
                v_edit_mode = false;
                [self.tableView setEditing:NO animated:YES];
                [self.rightBarItem updateTitle:NSLocalizedString(@"jrd_edit", nil)];
            }
            
        }];
    }
}

- (void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self setupTableview];
}

- (void)loadNewData{
    //end refersh because use fake data
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseChapterData];
    });
}

- (void)sortNodeList{
    //dispatch_async(dispatch_get_global_queue(0, 0), ^{
    for(int i = 0; i < nodeListData.count; i ++){
        NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                      nodeListData[i][NODE_ID],[JrdDatamanager manager].user.userId];
        NSArray*  childNode = (NSMutableArray* )[manager searchDataFromSheet:@"nodelist" where:searchCondition];
        
        if(nil != childNode && 0 !=childNode.count){
            for(int j= 0 ; j< childNode.count; j++){
                [nodeListData insertObject:childNode[j] atIndex:(i+1)];
                [self.songArray insertObject:childNode[j] atIndex:(i+1)];
            }
        }
    }
}




- (void)getCourseChapterData{
    NSDictionary *parameter = @{@"courseid":_coursemodel.courseId};
    __weak typeof(self) weakself = self;
    [CKHttpCommunicate createRequest:HTTP_CHAPTER_DATA WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            nodeList= result;
            if(0 != nodeList){
                for(int i = 0; i < nodeList.count; i++){
                    //insert node into node list
                    //NSString * searchCondition = [NSString stringWithFormat:@"node_name='%@' and user_id=%@",
                    //[nodeList[i] valueForKey:@"name"],[JrdDatamanager manager].user.userId];
                    NSString * searchCondition = [NSString stringWithFormat:@"node_id='%@' and node_parentid= '%@' and user_id=%@",[nodeList[i] valueForKey:@"id"],[nodeList[i] valueForKey:@"parent_id"],[JrdDatamanager manager].user.userId];

                    NSArray* array = [manager searchDataFromSheet:@"nodelist" where:searchCondition];
                    if(nil == array|| 0 == array.count){
                        Boolean ret = [manager insertDataToSheetWithAuto:@"nodelist" withData:@[
                                 [nodeList[i] valueForKey:@"id"],
                                 [JrdDatamanager manager].user.userId,
                                  [nodeList[i] valueForKey:@"name"],
                                  [nodeList[i] valueForKey:@"audio_url"],
                                  [nodeList[i] valueForKey:@"doc_url"],
                                  @"nodes",
                                  [nodeList[i] valueForKey:@"parent_id"],//self.coursemodel.courseId,
                                  @(0),
                                  @(0),
                                  @(0), // isdownload
                                  @"",  //downloadurl
                                  [nodeList[i] valueForKey:@"level_id"],
                                ]];
                        NSLog(@"ret = %d", ret);
                    }else{
                        Boolean ret = [manager updateDataToSheet_CourseDetail:@"nodelist" withData:@[
                                    [nodeList[i] valueForKey:@"name"],
                                    [nodeList[i] valueForKey:@"audio_url"],
                                    [nodeList[i] valueForKey:@"doc_url"]]
                                    where:searchCondition];
                        NSLog(@"ret = %d", ret);
                    }
                }
            }else{
            
            }
            NSLog(@"zlwu add for test");
            //nodeListData = [manager getSheetDataWithSheet:@"nodelist"];
            NSString * searchCondition = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                          _coursemodel.courseId,[JrdDatamanager manager].user.userId];
            nodeListData = (NSMutableArray* )[manager searchDataFromSheet:@"nodelist" where:searchCondition];
            
            if(nil != nodeListData && 0 != nodeListData.count){
                [self.songArray removeAllObjects];
                for(int i =0; i < nodeListData.count; i++){
                    MusicModel *model = [[MusicModel alloc] init];
                    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
                    model.course_id = [numberFormatter numberFromString:_coursemodel.courseId];
                    model.chapter_id = [NSNumber numberWithInt:0];
                    model.music_id = nodeListData[i][0];
                    model.fileName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_AUDIO_URL]];
                    model.docName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_DOC_URL]];
                    model.singer = nodeListData[i][NODE_LEVEL_ID];

                    if(1 == [nodeListData[i][NODE_IS_DOWNLOAD] intValue]){
                        model.localPath = nodeListData[i][NODE_DOWNLOAD_URL];
                    }

                    [self.songArray addObject:model];
                }
            }

            [self sortNodeList];
        }
        [weakself.tableView reloadData];
        [weakself.tableView.mj_header endRefreshing];
    } failure:^(NSError *erro) {
        [weakself.tableView.mj_header endRefreshing];
        
    } showHUD:nil];
    
}

- (void)setupTableview{
    if(ENTER_FROM_DOWNLOAD != _enter_type){
        MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        //设置普通状态的动画图片
        NSMutableArray *idleImages = [NSMutableArray array];
        for (NSUInteger i = 1; i<=60; ++i) {
            UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
            [idleImages addObject:image];
        }
        [header setImages:idleImages forState:MJRefreshStateIdle];
        
        //设置即将刷新状态的动画图片
        NSMutableArray *refreshingImages = [NSMutableArray array];
        UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [refreshingImages addObject:image1];
        UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
        [refreshingImages addObject:image2];
        [header setImages:refreshingImages forState:MJRefreshStatePulling];
        [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
        
        self.tableView.mj_header = header;
        //马上进入刷新状态
        //[self.tableView.mj_header beginRefreshing];
        if(nil == nodeListData || 0 == nodeListData.count){
            [self loadNewData];
        }

    }
    //[self.tableView setEditing:YES animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(true == v_is_has_date){
        if(0 == section ||1 ==section){
            return 1;
        }else {
            if(0 != nodeListData.count){
                return nodeListData.count;
            }else{
                return chapterListArray.count;
            }
        }

        
    }else{
        if(0 == section){
            return 1;
        }else {
            if(0 != nodeListData.count){
                return nodeListData.count;
            }else{
                return chapterListArray.count;
            }
        }

    }
}


// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(true == v_is_has_date){
        return 3;
    }else{
        return 2;
    }
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(0 == indexPath.section || (1== indexPath.section && true == v_is_has_date)){
        static NSString *cellIndentifier = @"detailCell0";
        UITableViewCell* cell  =[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        if(0 == indexPath.row){
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            //[cell addSubview:lineView];
            
            UIView *lineView_foot = [[UIView alloc] initWithFrame:CGRectMake(0, vCourseInfoCellHeight - 0.5, SCREEN_WIDTH, 0.5)];
            lineView_foot.tag = 10;
            lineView_foot.backgroundColor = JrdSpeLineColor;
            //[cell addSubview:lineView_foot];
        }else{
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 49.5, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
            
        }
        
        //if(0 == indexPath.row){
            cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
            cell.textLabel.numberOfLines = 0;
        if(0 == indexPath.section){
            cell.textLabel.text = _coursemodel.courseDes;//@"这是课程简介";
        }else{
            cell.textLabel.text = [NSString stringWithFormat:@"%@ ~ %@",_coursemodel.courseStartTime,_coursemodel.courseEndTime];
        }
        cell.userInteractionEnabled = NO;
        return cell;
    }else{
        static NSString *cellIndentifier = @"detailCell11";//[NSString stringWithFormat:@"detailCell11%@%@",indexPath.section,indexPath.row];//@"detailCell11";
        
        JrdCourseNodeCellTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];//[tableView dequeueReusableCellWithIdentifier:cellIndentifier];

        if (cell == nil) {
            cell = [[JrdCourseNodeCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
            //下划线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(40, 63.5, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
        }/*else{
            while ([cell.contentView.subviews lastObject] != nil) {
                [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
            }
        }*/
        
        JrdNodeModel* chapterModel = [[JrdNodeModel alloc] init];
        chapterModel.NodeID = nodeListData[indexPath.row][NODE_ID];
        chapterModel.NodeName = nodeListData[indexPath.row][NODE_NAME];//[nodeList[indexPath.row] valueForKey:@"name"];
        chapterModel.NodeDocUrl = nodeListData[indexPath.row][NODE_DOC_URL];//[nodeList[indexPath.row] valueForKey:@"doc_url"];
        chapterModel.NodeMp3Url = nodeListData[indexPath.row][NODE_AUDIO_URL];//[nodeList[indexPath.row] valueForKey:@"audio_url"];
        chapterModel.NodeIndex = indexPath.row + 1;
        NSString* studyLen= nodeListData[indexPath.row][NODE_STUDY_TIME];
        chapterModel.NodeStudyLength = [studyLen floatValue];//nodeListData[indexPath.row][7];//学习时长
        NSString* totalLen= nodeListData[indexPath.row][NODE_TOTAL_TIME];
        chapterModel.NodeDuration = [totalLen floatValue];
        chapterModel.NodeIsDownload = nodeListData[indexPath.row][NODE_IS_DOWNLOAD];
        //NSLog(@"zlwu add for download url , idnex = %ld",(long)indexPath.row);
        chapterModel.NodeDownloadUrl = nodeListData[indexPath.row][NODE_DOWNLOAD_URL];
        chapterModel.NodeLevelId = nodeListData[indexPath.row][NODE_LEVEL_ID];
        if(ENTER_FROM_NORMAL == _enter_type){
            [cell setJzClassM:chapterModel isShowDownload:true];
        }else{
            [cell setJzClassM:chapterModel];
        }
        UIButton* image= [[UIButton alloc] initWithFrame:CGRectMake(/*SCREEN_WIDTH - 36*/0, 22, 25, 25)];
        image.tag = indexPath.row+200;
        
        if(0 == [chapterModel.NodeLevelId intValue]){
            if(ENTER_FROM_VIEWONLY != _enter_type){
                //
                NSString * searchCondition = [NSString stringWithFormat:@"question_node_id=%@ and user_id=%@",
                                              chapterModel.NodeID,[JrdDatamanager manager].user.userId];
                
                NSArray* nodeListData_= [manager searchDataFromSheet:@"question_list" where:searchCondition];
                NSString* scoreString;
                int score = 0;
                for(int i= 0; i < nodeListData_.count; i++){
                    //NSString* score = nodeListData[i][3];
                    score += [nodeListData_[i][QUESTION_VALUE] intValue];
                }
                scoreString = [NSString stringWithFormat:@"%d分", score];
                [image setFrame:CGRectMake(/*SCREEN_WIDTH - 36*/0, 22, 40, 20)];
                
                [image setTitle:scoreString forState:UIControlStateNormal];
                [image.titleLabel setFont:[UIFont systemFontOfSize:12.f]];
                [image setTitleColor:JrdBlackColor forState:UIControlStateNormal];
                cell.accessoryView = image;
            }
        }else{
            if( ENTER_FROM_VIEWONLY != _enter_type){
                if(ENTER_FROM_NORMAL == _enter_type && 1!=[chapterModel.NodeIsDownload intValue]){
                    [image setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
                    [image addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
                    cell.accessoryView = image;
                }
                else{
                    [image setFrame:CGRectMake(/*SCREEN_WIDTH - 56*/0, 22, 40, 20)];
                    [image setTitle:@"已下载" forState:UIControlStateNormal];
                    [image.titleLabel setFont:[UIFont systemFontOfSize:12.f]];
                    [image setTitleColor:JrdBlackColor forState:UIControlStateNormal];
                    cell.accessoryView = image;
                }
            }

        }

        return cell;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 || indexPath.section == 0) {
        return NO;
    }
    return YES;
}
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath

{
    return NO;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  nodeListData[indexPath.row][NODE_ID],[JrdDatamanager manager].user.userId];
    
    //NSString* download_url = [NSString stringWithFormat:@"%@&%@",model.download_pre_filename, request.savePath];
    Boolean ret = [manager updateDataToSheet_DownloadUrl:@"nodelist" withData:@[@(0), @""] where:searchCondition];
    NSString* local_patch = nodeListData[indexPath.row][NODE_DOWNLOAD_URL];
    NSInteger index = [local_patch rangeOfString:@"&"].location;
    NSString* doc_url = [local_patch substringFromIndex:(index +1)];

    NSString* audio_url = [local_patch substringToIndex:index];
    /*remove file from filemanager*/
    
     NSFileManager * fileManager = [[NSFileManager alloc]init];
     [fileManager removeItemAtPath:audio_url error:nil];
    [fileManager removeItemAtPath:doc_url error:nil];

     
    
    [nodeListData removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

- (void)downloadClick:(UIButton*)sender{
    NSLog(@"zlwu download click");
    UIButton *button = (UIButton*)[self.view viewWithTag:sender.tag];
    select_index = (sender.tag-200);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_stop"] forState:UIControlStateNormal];
    NSString* url_string = nodeListData[select_index][NODE_AUDIO_URL];
    NSString* task_url = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_string];
    NSString* doc_name = [task_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    if([[NSUserDefaults standardUserDefaults] boolForKey:@"vDownloadUnderWifi"] == YES){
        NSString* currentState =  [self GetCurrntNet];
        if([currentState isEqualToString:@"wifi"]){
            //do nothing
        }else{
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_nowifi_title", nil) message:NSLocalizedString(@"jrd_nowifi_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
            alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
            alertView.tag = 0;
            [alertView show];
            return;
        }
    }
    JrdDownloadModel* model = [self findDownloadId:url_string];

    CLDownloadRequest *request = [CLDownloadRequest initWithURL:doc_name];
    
    if (CLDownloadRequestState_None == request.state && DOWNLOAD_NONE == model.download_status) {
        v_download_status = DOWNLOAD_AUDIO;
        JrdDownloadModel* model = [[JrdDownloadModel alloc] init];
        model.download_index = select_index;
        model.download_filename = url_string;
        model.download_status = v_download_status;
        [m_download_list addObject:model];

        request.delegate = self;
        request.httpMethod = @"GET";
        request.allowResume = YES;
        [request startDownload];
        return;
    }
    if(DOWNLOAD_AUDIO == model.download_status){
        if (!sender.selected) {
            NSLog(@"暂停...");
            [button setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
            button.selected  = YES;
            [request pauseDownload];
        }else {
            NSLog(@"恢复...");
            [button setBackgroundImage:[UIImage imageNamed:@"btn_stop"] forState:UIControlStateNormal];
            button.selected = NO;
            [request resumeDownload];
        }
    }else if(DOWNLOAD_PDF == model.download_status){
        NSString* url_string_pdf = nodeListData[select_index][NODE_DOC_URL];
        NSString* task_url_pdf = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_string_pdf];
        NSString* doc_name_pdf = [task_url_pdf stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        CLDownloadRequest *request_pdf = [CLDownloadRequest initWithURL:doc_name_pdf];
        if (!sender.selected) {
            NSLog(@"暂停...");
            [button setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
            button.selected  = YES;
            [request_pdf pauseDownload];
        }else {
            NSLog(@"恢复...");
            [button setBackgroundImage:[UIImage imageNamed:@"btn_stop"] forState:UIControlStateNormal];
            button.selected = NO;
            [request_pdf resumeDownload];
        }

    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(true == v_is_has_date){
        if(0 == section){
            return NSLocalizedString(@"jrd_course_des", nil);//@"课程简介";
        }else if(1 == section){
            return NSLocalizedString(@"jrd_ava_date", nil);//@"课程简介";

        }else{
            return NSLocalizedString(@"jrd_chapter", nil);//@"科目";
        }

    }else{
        if(0 == section){
            return NSLocalizedString(@"jrd_course_des", nil);//@"课程简介";
        }else{
            return NSLocalizedString(@"jrd_chapter", nil);//@"科目";
        }

    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            
            NSString *str = _coursemodel.courseDes;
            
            CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:18.f] constrainedToSize:CGSizeMake((SCREEN_WIDTH - 16), MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
            
            vCourseInfoCellHeight = size.height+20;
            return vCourseInfoCellHeight;
        }else{
            return 45;
        }
    }else{
        return 64;
    }
}

- (void)OnTap1{
    //vHeadIndex = 0;
    [self.tableView reloadData];
}

- (void)OnTap2{
    NSLog(@"onTap1");
    //vHeadIndex = 1;
    [self.tableView reloadData];
    
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
    if (section == 0) {
        return nil;
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
    headerView.backgroundColor = JrdNavigationBarColor;//JrdSelectColor;
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTap1)];
    //目录View
    UIView *view_1 = [[UIView alloc] initWithFrame:CGRectMake(2, 2, SCREEN_WIDTH/2 - 4, 55 - 4)];
    if(0 == vHeadIndex){ //view_1 highlight
        view_1.backgroundColor = JrdSelectColor;//JrdNavigationBarColor;
    }else{
        view_1.backgroundColor = [UIColor clearColor];
    }
    view_1.layer.cornerRadius = 1;
    // view_1.backgroundColor = JRD_RGB(100, 100, 100);
    
    //图
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 - 4 - 25)/2, 5 - 2, 25, 25)];
    [imageView1 setImage:[UIImage imageNamed:@"course_catalog_icon"]];
    //[imageView1 addGestureRecognizer:tap1];
    [view_1 addSubview:imageView1];
    //文字
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView1.frame), SCREEN_WIDTH/2 -4, 20)];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.textColor = [UIColor whiteColor];
    label1.font = [UIFont systemFontOfSize:13];
    label1.text = @"目录";
    //[label1 addGestureRecognizer:tap1];
    [view_1 addSubview:label1];
    [view_1 addGestureRecognizer:tap1];
    
    [headerView addSubview:view_1];
    
    //图
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTap2)];
    
    UIView *view_2 = [[UIView alloc] initWithFrame:CGRectMake(2 + (SCREEN_WIDTH/2), 2, SCREEN_WIDTH/2 - 4, 55 - 4)];
    if(1 == vHeadIndex){
        view_2.backgroundColor = JrdSelectColor;//JrdNavigationBarColor;
    }else{
        view_2.backgroundColor = [UIColor clearColor];//JRD_RGB(200, 200, 200);
        
    }
    view_2.layer.cornerRadius = 1;
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 -4 - 25)/2, 5 - 2, 25, 25)];
    [imageView2 setImage:[UIImage imageNamed:@"course_info_icon"]];
    imageView2.userInteractionEnabled = YES;
    [view_2 addSubview:imageView2];
    
    //文字
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView1.frame), SCREEN_WIDTH/2 -4, 20)];
    
    label2.textAlignment = NSTextAlignmentCenter;
    label2.textColor = [UIColor whiteColor];
    label2.font = [UIFont systemFontOfSize:13];
    label2.text = @"详情";
    label2.userInteractionEnabled = YES;
    [view_2 addSubview:label2];
    [view_2 addGestureRecognizer:tap2];
    [headerView addSubview:view_2];
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"zlwu add for select index");
    if(DOWNLOAD_NONE!= v_download_status){
        //return;
    }

    if(ENTER_FROM_VIEWONLY == _enter_type){
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"jrd_couse_fuse_play", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_done", nil) otherButtonTitles:nil , nil];
        [alert show];
        return;
    }
    if(0 == [nodeListData[indexPath.row][NODE_LEVEL_ID] intValue]){
        //Go to test screen
        JrdQuestionViewController* viewController= [[JrdQuestionViewController alloc] init];
        JrdNodeModel* chapterModel = [[JrdNodeModel alloc] init];
        chapterModel.NodeID = nodeListData[indexPath.row][NODE_ID];
        chapterModel.NodeName = nodeListData[indexPath.row][NODE_NAME];//[nodeList[indexPath.row] valueForKey:@"name"];
        chapterModel.NodeDocUrl = nodeListData[indexPath.row][NODE_DOC_URL];//[nodeList[indexPath.row] valueForKey:@"doc_url"];
        chapterModel.NodeMp3Url = nodeListData[indexPath.row][NODE_AUDIO_URL];//[nodeList[indexPath.row] valueForKey:@"audio_url"];
        chapterModel.NodeIndex = indexPath.row + 1;
        NSString* studyLen= nodeListData[indexPath.row][NODE_STUDY_TIME];
        chapterModel.NodeParentID = nodeListData[indexPath.row][NODE_PARENTID];
        chapterModel.NodeStudyLength = [studyLen floatValue];//nodeListData[indexPath.row][7];//学习时长
        NSString* totalLen= nodeListData[indexPath.row][NODE_TOTAL_TIME];
        chapterModel.NodeDuration = [totalLen floatValue];
        chapterModel.NodeIsDownload = nodeListData[indexPath.row][NODE_IS_DOWNLOAD];
        chapterModel.NodeDownloadUrl = nodeListData[indexPath.row][NODE_DOWNLOAD_URL];
        chapterModel.NodeLevelId = nodeListData[indexPath.row][NODE_LEVEL_ID];
        

        [viewController setDetailClassM:chapterModel];
        [self.navigationController pushViewController:viewController animated:YES];
        return;
    }
    if((((1 == indexPath.section)&& false ==v_is_has_date)||((2==indexPath.section) && true == v_is_has_date)) && 0 == vHeadIndex){
        //判断，如果处于 仅wifi下播放，且当前状态不是wifi状态下，弹出警告框
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"vDownloadUnderWifi"] == YES){
            NSString* currentState =  [self GetCurrntNet];
            //currentState = @"4G";
            //check课程是否已经下载，如果已经下载，即可播放
            NSString* is_download = nodeListData[indexPath.row][NODE_IS_DOWNLOAD];
            if([is_download isEqualToString:@"1"]){
                AudioPlayerController *audio = [AudioPlayerController audioPlayerController];
                [audio initWithArray:self.songArray index:indexPath.row];
                [self presentViewController:audio animated:YES completion:nil];
            }else{
                if(nil == currentState){
                    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_nowifi_title", nil) message:NSLocalizedString(@"jrd_nowifi_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
                    alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
                    alertView.tag = 0;
                    [alertView show];
                    
                }else if([currentState isEqualToString:@"wifi"]){
                    AudioPlayerController *audio = [AudioPlayerController audioPlayerController];
                    [audio initWithArray:self.songArray index:indexPath.row];
                    [self presentViewController:audio animated:YES completion:nil];
                }else{
                    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"jrd_nowifi_title", nil) message:NSLocalizedString(@"jrd_nowifi_message", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
                    alertView.frame  = CGRectMake((SCREEN_WIDTH - 200)/2, (SCREEN_HEIGHT - 150)/2, 200, 100);
                    alertView.tag = 0;
                    [alertView show];
                }
            }
        }else{
            AudioPlayerController *audio = [AudioPlayerController audioPlayerController];
            [audio initWithArray:self.songArray index:indexPath.row];
            [self presentViewController:audio animated:YES completion:nil];
        }
    }
    
    
}

- (void)setFakeData
{
    [self dataJson];
}


#pragma mark - Mark data
- (NSMutableArray *)songArray
{
    if (!_songArray) {
        _songArray = [NSMutableArray array];
    }
    return _songArray;
}

-(void)dataJson
{
    NSString *str = [[NSBundle mainBundle]pathForResource:@"musicPaper" ofType:@"json"];
    NSData *data = [[NSData alloc]initWithContentsOfFile:str];
    
    NSMutableArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@,  ---%ld",dataArray, (unsigned long)dataArray.count);
    //    [self.songArray addObject:dic];
    for (NSDictionary *dic in dataArray) {
        MusicModel *model = [[MusicModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.songArray addObject:model];
    }
    //[self.songTableView reloadData];
}


-(NSString*)GetCurrntNet

{
    
    NSString* result;
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    
    switch ([r currentReachabilityStatus]) {
            
        case NotReachable:// 没有网络连接
            
            result=nil;
            
            break;
            
        case ReachableViaWWAN:// 使用3G网络
            
            result=@"3g";
            
            break;
            
        case ReachableViaWiFi:// 使用WiFi网络
            
            result=@"wifi";
            
            break;
            
    }
    
    return result;
}

- (JrdDownloadModel*)findDownloadId:(NSString*)saveName{
    JrdDownloadModel *model = nil;
    for(int i= 0; i < m_download_list.count; i++)
    {
        model = [m_download_list objectAtIndex:i];
        
        if([model.download_filename containsString:saveName] || [model.download_pdf_filename containsString: saveName]){
            model.index = i;
            return model;
        }
    }
    //return index;
    return nil;
}

#pragma download
- (void)requestDownloadStart:(CLDownloadRequest *)request
{
    
    /*JrdDownloadModel* model = [self findDownloadId:request.saveFileName];
    if(nil == model)
    {
        return;
    }*/
    //UIButton *button = (UIButton*)[self.view viewWithTag:(model.download_index + 200)];
   // click_cell  = (JrdCourseNodeCellTableViewCell*)button.superview;
    
    //if(DOWNLOAD_AUDIO == model.download_status){
      //  click_cell.taskProgressLabel.text= @"start";
    //}
    //click_cell.taskProgressLabel.hidden = NO;
}
- (void)requestDownloading:(CLDownloadRequest *)request
{
    JrdDownloadModel* model = [self findDownloadId:request.saveFileName];
    if(nil == model)
    {
        return;
    }

    UIButton *button = (UIButton*)[self.view viewWithTag:(model.download_index + 200)];
    click_cell  = (JrdCourseNodeCellTableViewCell*)button.superview;
    click_cell.taskProgress.hidden = NO;
    click_cell.taskProgressLabel.hidden = NO;
    if(DOWNLOAD_AUDIO == model.download_status){
        click_cell.taskProgress.progress = request.progress/2;
        click_cell.taskProgressLabel.text = [NSString stringWithFormat:@"%0.2f%%",request.progress*50];
    }else if(DOWNLOAD_PDF == model.download_status){
        click_cell.taskProgress.progress = 0.5+ request.progress/2;
        click_cell.taskProgressLabel.text = [NSString stringWithFormat:@"%0.2f%%",request.progress*50+50];
    }
}

- (void)requestDownloadFinish:(CLDownloadRequest *)request
{
    JrdDownloadModel* model = [self findDownloadId:request.saveFileName];
    if(nil == model)
    {
        return;
    }

    if(model.download_status == DOWNLOAD_PDF && ![request.saveFileName containsString:@"pdf"]){
        return;
    }
    if(model.download_status  == DOWNLOAD_AUDIO){
        model.download_pre_filename = request.savePath;
        
        NSString* url_string = nodeListData[select_index][NODE_DOC_URL];
        NSString* task_url = [NSString stringWithFormat:@"http://120.55.86.220/%@",url_string];
        NSString* doc_name = [task_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        CLDownloadRequest *request = [CLDownloadRequest initWithURL:doc_name];
        if (CLDownloadRequestState_None == request.state) {
            model.download_status = DOWNLOAD_PDF;
            model.download_pdf_filename = url_string;

            request.delegate = self;
            request.httpMethod = @"GET";
            request.allowResume = YES;
            [request startDownload];
            return;
        }

    }
    [m_download_list removeObjectAtIndex:model.index];
    UIButton *button1 = (UIButton*)[self.view viewWithTag:(model.download_index + 200)];
    click_cell  = (JrdCourseNodeCellTableViewCell*)button1.superview;

    click_cell.taskProgress.hidden= YES;
    UIButton *button = (UIButton*)[self.view viewWithTag:(model.download_index + 200)];
    
    //button.hidden = YES;
    [button setFrame:CGRectMake(SCREEN_WIDTH - 56, 22, 40, 20)];
    [button setBackgroundImage:nil forState:UIControlStateNormal];
    [button setTitle:@"已下载" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:12.f]];
    [button setTitleColor:JrdBlackColor forState:UIControlStateNormal];
    
    model.download_status = DOWNLOAD_NONE;
    click_cell.taskProgressLabel.text = @"";//@"100%";
    //update data
    NSString * searchCondition = [NSString stringWithFormat:@"node_id=%@ and user_id=%@",
                                  nodeListData[select_index][NODE_ID],[JrdDatamanager manager].user.userId];

    NSString* download_url = [NSString stringWithFormat:@"%@&%@",model.download_pre_filename, request.savePath];
    Boolean ret = [manager updateDataToSheet_DownloadUrl:@"nodelist" withData:@[@(1), download_url] where:searchCondition];
    NSLog(@"ret = %d", ret);
    NSString * searchConditionExt = [NSString stringWithFormat:@"course_id=%@ and user_id=%@",
                                  _coursemodel.courseId, [JrdDatamanager manager].user.userId];
    Boolean retExt = [manager updateDataToSheet_couse_download:@"courselist" withData:@[@(1)] where:searchConditionExt];
    NSLog(@"%d", retExt);
    

    [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateDownloadInfoNotification object:self];
    
    
    NSString * searchCondition1 = [NSString stringWithFormat:@"node_parentid=%@ and user_id=%@",
                                  _coursemodel.courseId, [JrdDatamanager manager].user.userId];

    nodeListData= (NSMutableArray*)[manager searchDataFromSheet:@"nodelist" where:searchCondition1];
    [self sortNodeList];

    if(nil != nodeListData && 0 != nodeListData.count){
        [self.songArray removeAllObjects];
        for(int i =0; i < nodeListData.count; i++){
            MusicModel *model = [[MusicModel alloc] init];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            model.course_id = [numberFormatter numberFromString:_coursemodel.courseId];
            model.chapter_id = [NSNumber numberWithInt:0];
            model.music_id = nodeListData[i][NODE_ID];
            model.fileName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_AUDIO_URL]];
            model.docName = [NSString stringWithFormat:@"http://120.55.86.220/%@",nodeListData[i][NODE_DOC_URL]];
            model.singer = nodeListData[i][NODE_LEVEL_ID];
            if(1 == [nodeListData[i][NODE_IS_DOWNLOAD] intValue]){
                model.localPath = nodeListData[i][NODE_DOWNLOAD_URL];
            }
            [self.songArray addObject:model];
        }
    }

}

- (void)requestDownloadFaild:(CLDownloadRequest *)request aError:(NSError *)error
{
    //UILabel* label = (UILabel*)[self.view viewWithTag:(select_index +60)];
    //label.text = @"fail";
    JrdDownloadModel* model = [self findDownloadId:request.saveFileName];
    if(nil == model)
    {
        return;
    }
    UIButton *button1 = (UIButton*)[self.view viewWithTag:(model.download_index + 200)];
    click_cell  = (JrdCourseNodeCellTableViewCell*)button1.superview;
    click_cell.taskProgressLabel = @"fail";
    click_cell.taskProgress.hidden = YES;
    [button1 setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
    button1.selected  = YES;

    model.download_status = DOWNLOAD_NONE;
    //如果出错了，删除目标文件
    NSFileManager * fileManager = [[NSFileManager alloc]init];
    //NSString* savePath = [self downLoadFilePath];
    BOOL ret = [fileManager removeItemAtPath:[error.userInfo valueForKey:@"NSDestinationFilePath"] error:nil];
}

- (void)requestDownloadPause:(CLDownloadRequest *)request
{
    UILabel* label = (UILabel*)[self.view viewWithTag:(select_index +60)];
    label.text = @"pause";
}

- (void)requestDownloadCancel:(CLDownloadRequest *)request
{
    NSLog(@"download Cancel fileName: %@",request.saveFileName);
}
@end
